package net.fltx.dm;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Variant;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class DmProxy implements InvocationHandler {

    private ActiveXComponent activeXComponent;
    private Dm dm;
    private String className="dm.dmsoft";
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Variant result=null;
        if(args==null){
            result= activeXComponent.invoke(method.getName());
        }else {
            Variant[] variant =new Variant[args.length];
            for (int i = 0; i < args.length; i++) {
                if(args[i] instanceof Variant){
                    variant[i]= (Variant) args[i];
                }else {
                    variant[i]=new Variant(args[i]);
                }
            }
            result= activeXComponent.invoke(method.getName(),variant);
        }
        return result.toJavaObject();
    }


    public synchronized Dm getDmInstance(){
        if(activeXComponent==null){
            activeXComponent=new ActiveXComponent(className);
        }

        if(dm==null) {
            dm = (Dm) Proxy.newProxyInstance(
                    Dm.class.getClassLoader(),
                    new Class[]{Dm.class},
                    this);
        }
        return dm;
    }

}
